module ESI
  class BaseParser
    attr_reader :router, :cache

    def initialize(router,cache)
      @cache = cache
      @router = router
    end

    # :startdoc:
    # scans the fragment url, replacing occurrances of $(VAR{ ..  with the given value read from
    # the HTTP Request object
    # :enddoc:
    def prepare_url_vars(url,params)
      # scan url  for $(VAR{
      # using the regex look for url vars that get set via http params
      # for each var extract the value and store it in the operations array
      operations = []
      url.scan(/\$\([0-9a-zA-Z_{}]+\)/x) do|var|
        # extract the var name
        name = var.gsub(/\$\(/,'').gsub(/\{.*$/,'')
        key = var.gsub(/^.*\{/,'').gsub(/\}.*$/,'')
        value = Mongrel::HttpRequest.query_parse(params[name])[key]
        operations << {:sub => var, :with => (value||"")}
      end
      # apply each operation to the url
      operations.each { |op| url.gsub!(op[:sub],op[:with]) }
      url
    end
  end
end
